package com.mmall.demo2.controller;

import com.mmall.demo2.model.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * @Auther guo
 * @Date 2018/12/15 12:08
 * @Description $end$
 */

@Controller
public class TestController {

    @RequestMapping("/login")
    public String login(){
        return "login";
    }
    @RequestMapping("/unauthorized")
    public String unauthorized(){

        return "unauthorized";
    }

    @RequestMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        if (subject == null) {
            subject.logout();;
        }
        return "login";
    }


    @RequestMapping("/index")
    public String index(){

        return "index";
    }


    @RequestMapping("/edit")
    @ResponseBody
    public String edit(){
        return "edit";
    }

    @RequestMapping("/admin")
    @ResponseBody
    public String admin(){

        return "admin success";
    }

    @RequestMapping("/loginUser")
    @ResponseBody
    public String loginUser(@RequestParam("username") String username,
                            @RequestParam("password") String password,
                            HttpSession session){

        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            User user = (User) subject.getPrincipal();
            session.setAttribute("user",user);
        } catch (UnknownAccountException e) {
            return  "账号不存在";
        } catch (IncorrectCredentialsException e) {
            return  "用户名或者密码错误";
        }
        return "登录信息验证成功";
    }


}
